 /*   
 * Project: OSMP
 * FileName: DeviceController.java
 * version: V1.0
 */
package com.cnpc.iot.scene.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cnpc.framework.annotation.VerifyCSRFToken;
import com.cnpc.framework.base.entity.Dict;
import com.cnpc.framework.base.pojo.Result;
import com.cnpc.framework.base.service.BaseService;
import com.cnpc.framework.utils.HttpClientUtil;
import com.cnpc.framework.utils.PropertiesUtil;
import com.cnpc.iot.scene.entity.Device;
import com.cnpc.iot.scene.entity.Sensor;
import com.cnpc.iot.scene.service.DeviceService;
import com.cnpc.iot.scene.vo.SensorVo;

import static com.cnpc.framework.utils.HttpClientUtil.doGet;
import static sun.audio.AudioDevice.device;

 /**
 * Description:
 * @author: wangkaiping
 * @date: 2018年2月27日 下午4:57:51上午10:51:30
 */
@Controller
@RequestMapping("/device")
public class DeviceController {

	@Resource
    private BaseService baseService;
	@Resource
	private DeviceService deviceService;

	@RequestMapping(value="/cameraShow",method = RequestMethod.GET)
    public String cameraShow(String deviceId,HttpServletRequest request){
		Device device = baseService.get(Device.class, deviceId);
		request.setAttribute("device", device);
        return "iot/data/camera_show";
    }
	
	@RequestMapping(value="/edit",method = RequestMethod.GET)
    public String toEdit(String id,HttpServletRequest request){
		request.setAttribute("id", id);
        return "iot/scene/device_edit";
    }
	
	@RequestMapping(value="/sensorAdd",method = RequestMethod.GET)
    public String sensorAdd(String id,HttpServletRequest request){
		request.setAttribute("deviceId", id);
        return "iot/scene/sensor_edit";
    }
	
	@RequestMapping(value="/sensorEdit",method = RequestMethod.GET)
    public String sensorEdit(String id,HttpServletRequest request){
		Sensor sensor = baseService.get(Sensor.class, id);
		request.setAttribute("id", id);
		request.setAttribute("deviceId", sensor.getDeviceId());
        return "iot/scene/sensor_edit";
    }
	
    @RequestMapping(value="/get/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Device get(@PathVariable("id") String id){
    	if(id.startsWith("dev_")) {
    		id = id.replaceAll("dev_", "");
    	}
        return baseService.get(Device.class, id);
    }
    
    @RequestMapping(value="/getSensor/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Sensor getSensor(@PathVariable("id") String id){
        return baseService.get(Sensor.class, id);
    }
    
    @VerifyCSRFToken
    @RequestMapping(value="/save")
    @ResponseBody
    public Result save(Device device){
        Device temp = baseService.get(Device.class, device.getId());
        temp.setDevip(device.getDevip());
        temp.setPort(device.getPort());
        temp.setRemark(device.getRemark());
        temp.setName(device.getName());
        temp.setPa(device.getPa());
        temp.setPb(device.getPb());
        baseService.update(temp);
        return new Result(true);
    }
    
    @VerifyCSRFToken
    @RequestMapping(value="/saveSensor")
    @ResponseBody
    public Result saveSensor(String obj){
    	Sensor sensor= JSON.parseObject(obj,Sensor.class);
    	Dict type = baseService.get(Dict.class,sensor.getType().getId());
    	sensor.setType(type);
    	String[] temp = type.getRemark().split(",");
    	if(null == sensor.getIoPort()) {
    		sensor.setIoPort(Integer.parseInt(type.getCode()));
    	}
    	if(null == sensor.getLivalue()) {
    		sensor.setLivalue(Integer.parseInt(type.getValue()));
    	}
    	if(StringUtils.isEmpty(sensor.getUnit())) {
    		sensor.setUnit(temp[0]);
    	}
    	if(StringUtils.isEmpty(sensor.getIcon())) {
    		sensor.setIcon(temp[1]);
    	}
    	if(StringUtils.isEmpty(sensor.getId())){
    		baseService.save(sensor);
    	}else{
    		baseService.update(sensor);
    	}
        return new Result(true);
    }
    
    @RequestMapping(value="/delete/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@PathVariable("id") String id){
        List<Sensor> sensors =baseService.find("from Sensor where deviceId='"+id+"'");
        if(null != sensors && !sensors.isEmpty()){
            return new Result(false,"请先删除对应的传感器后再删除");
        }
        Device device=baseService.get(Device.class, id);
        try{
            baseService.delete(device);
            return new Result(true);
        }catch(Exception e){
            return new Result(false,"该数据已经被引用，不可删除");
        }
    }

    /**
     * 清除采集器缓存
     * @param id
     * @return
     */
    @RequestMapping(value="/sync_collector/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Result sync_collector(@PathVariable("id") String id){
        String collectorHost = PropertiesUtil.getValue("collector.url");
        HttpClientUtil.doGet(collectorHost+"/system/cleanDeviceMapping");
        return new Result(true);
    }

    @RequestMapping(value="/deleteSensor/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Result deleteSensor(@PathVariable("id") String id){
        Sensor sensor=baseService.get(Sensor.class, id);
        try{
            baseService.delete(sensor);
            return new Result(true);
        }
        catch(Exception e){
            return new Result(false,"该数据已经被引用，不可删除");
        }
    }

    @RequestMapping(value="/getSensorByDevice/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Result getSensorByDevice(@PathVariable("id") String id){
        List<SensorVo> sensors = deviceService.getMetric(id);
        Result result = new Result();
    	if(null != sensors && sensors.size() > 0) {
    		result.setSuccess(true);
    		result.setData(sensors);
    	}else {
    		result.setSuccess(false);
    	}
    	return result;
    }
    
    @RequestMapping(value="/getCollectDevice/{orgId}",method = RequestMethod.POST)
    @ResponseBody
    public Result getCollectDeviceByOrgId(@PathVariable("orgId") String orgId){
        List<Device> devices = baseService.find("from Device where orgid='"+orgId+"' and type='采集器'");
        Result result = new Result();
    	if(null != devices && devices.size() > 0) {
    		Device device= devices.get(0);
    		result.setSuccess(true);
    		result.setData(device.getDevip()+device.getPort());
    	}else {
    		result.setSuccess(false);
    	}
    	return result;
    }
    
}
